<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import useUserStore from '@/stores/useUserStore.js'
import RecursionMenu from '@/components/Home/RecursionMenu.vue'

const userStore = useUserStore()
const router = useRouter()
const breadList = ref([])

const logout = () => {
  ElMessageBox.confirm(
    '确定退出登录吗',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      userStore.deleteToken()
      userStore.deleteUser()
      router.push({ name: 'Login' })
    })
    .catch(() => {
    })
}

watch(() => router.currentRoute.value, (n, o) => {
  const obj = {
    title: n.meta.title,
    path: n.path,
    id: n.meta.id
  }
  if (breadList.value.length <= 0) {
    breadList.value.push(obj)
  }
  else {
    if (breadList.value.every(item => {
      return item.id !== n.meta.id
    })) {
      breadList.value = [obj]
    }
    else {
      const findResultIndex = breadList.value.findIndex(item => {
        return item.path === n.path
      })
      if (findResultIndex >= 0) {
        breadList.value = breadList.value.slice(0, findResultIndex + 1)
      }
      else {
        breadList.value.push(obj)
      }
    }
  }
}, {
  immediate: true
})
</script>

<template>
  <el-container>
    <el-aside width="300px">
      <div class="top">
        <img src="@/assets/logo.png">
        <h1>茶千道商家中心</h1>
      </div>
      <div class="body">
        <el-scrollbar>
          <RecursionMenu />
        </el-scrollbar>
      </div>
      <div class="bottom">
        <span>{{ userStore.user.employeeName }}</span>
        <span class="role">{{ userStore.user.employeeRole }}</span>
        <el-button type="info" size="default" @click="logout">退出登录</el-button>
      </div>
    </el-aside>
    <el-main>
      <el-scrollbar>
        <el-breadcrumb separator="/" style="margin-bottom: 10px;">
          <el-breadcrumb-item v-for="item in breadList" :key="item.path" :to="{ path: item.path }">{{ item.title
            }}</el-breadcrumb-item>
        </el-breadcrumb>
        <router-view></router-view>
      </el-scrollbar>
    </el-main>
  </el-container>
</template>

<style scoped lang="scss">
.el-container {
  height: 100vh;
  background-color: #f7f7f7;

  .el-aside {
    display: flex;
    flex-direction: column;
    background-color: #fff;

    .top {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 50px 0;

      img {
        width: 80px;
      }
    }

    .body {
      height: 566px;
    }

    .bottom {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      border-top: 1px solid #eee;

      .role {
        margin: 15px 0;
        color: #aaa;
        font-size: 14px;
      }
    }
  }
}
</style>
